﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using NigiriClub.WebUI.Models;
using NigiriClub.WebUI.Models.PagedCollections;

namespace NigiriClub.WebUI.Models
{
    public partial class News
    {
        public string Tags { get; set; }
        public int ChoosedId { get; set; }
        public List<Tag> TagList { get; set; }

        public IEnumerable<Category> CategoryList
        {
            get
            {
                IEnumerable<Category> list;
                using (Entities db = new Entities())
                {
                    list = db.Category.ToList();
                }
                return list;
            }
        }

        private void FillTags(Entities db)
        {
            string[] separators = new string[2] { "#", " " };
            string[] strings = this.Tags.Split(separators, StringSplitOptions.RemoveEmptyEntries);
            this.Tag.Clear();
            foreach (var tag in Models.Tag.GetTags(db, strings))
            {
                this.Tag.Add(tag);
            }
        }

        public void AddToDb(string userName)
        {
            using (Entities db = new Entities())
            {
                Account account = db.Account.FirstOrDefault(u => u.Name == userName);
                this.Date = DateTime.Now;
                this.Account = account;
                this.FillTags(db);
                db.News.Add(this);
                db.SaveChanges();
            }
        }

        public void Edit()
        {
            using (Entities db = new Entities())
            {
                News edited = db.News.FirstOrDefault(n => n.Id == this.Id);
                if (edited == null)
                {
                    //todo error message
                    return;
                }
                edited.Title = this.Title;
                edited.Body = this.Body;
                edited.CategoryId = this.CategoryId;
                edited.Tags = this.Tags;
                edited.FillTags(db);
                db.SaveChanges();
            }
        }
    }
}